<?php

class RRule {

    /**
     * Convert View select box elements into RRULE
     * 
     * @assert("M","SU","1","1") == "FREQ=MONTHLY;BYMONTHDAY=1"
     * @assert("M","SU","1","25") == "FREQ=MONTHLY;BYMONTHDAY=25"
     * @assert("M","SU","6","22") == "FREQ=MONTHLY;BYMONTHDAY=22"
     * @assert("M","SU","12","6") == "FREQ=MONTHLY;BYMONTHDAY=6"
     * @assert("W","SU","1","1") == "FREQ=WEEKLY;BYDAY=SU"
     * @assert("W","WE","1","1") == "FREQ=WEEKLY;BYDAY=WE"
     * @assert("W","FR","1","1") == "FREQ=WEEKLY;BYDAY=FR"
     */
    public function inputs_to_rrule($freq, $by_day, $by_month, $by_month_day) {

        switch ($freq) {
            case 'M':
                return 'FREQ=MONTHLY;BYMONTHDAY=' . $by_month_day;
                break;
            case 'W':
                return 'FREQ=WEEKLY;BYDAY=' . $by_day;
                break;
            default:
                return '';
        }
    }

    /**
     * Convert the RRULE string into View select box elements
     * 
     */
    function rrule_to_inputs($rrule) {

        // Create return Array
        $return = array();

        // Split on the semi-colon
        $params = explode(';', $rrule);

        // Loop thru each Key/Value Pair
        foreach ($params as $kvpair) {

            // Split on the equals
            $kvlist = explode('=', $kvpair);

            // get and lowercase the key
            $key = strtolower($kvlist[0]);

            // Get the value
            $value = $kvlist[1];

            // Convert FREQ values
            switch ($value) {
                case 'MONTHLY':
                    $value = 'M';
                    break;
                case 'WEEKLY':
                    $value = 'W';
                    break;
            }

            // Build return array
            $return[$key] = $value;
        }


        return $return;
    }

}

